package com.example.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.common.Constants;
import com.example.demo.common.Result;
import com.example.demo.dto.UserDTO;
import com.example.demo.entity.User;
import com.example.demo.exception.ServiceException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.TokenUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean saveUser(User user) {
        return saveOrUpdate(user);
    }

    @Override
    public UserDTO login(UserDTO userDTO) {

        User one = getUserInfo(userDTO);

        if (one != null){
            BeanUtil.copyProperties(one,userDTO,true);
            //设置token
            String token = TokenUtils.getToken(one.getId().toString(), one.getPassword().toString());
            userDTO.setToken(token);
            return userDTO;
        }else {
            throw new ServiceException(Constants.SYSTEM_CUSTOM_ERROR,"用户名或密码错误！");
        }

    }

    @Override
    public User register(UserDTO userDTO) {

        User one = getUserInfo(userDTO);
        if (one == null){
            one = new User();
            BeanUtil.copyProperties(userDTO,one,true);

            save(one);
        }else {
            throw new ServiceException(Constants.SYSTEM_CUSTOM_ERROR,"用户已存在");
        }
        return one;

    }

    private User getUserInfo(UserDTO userDTO){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",userDTO.getUsername());
        queryWrapper.eq("password",userDTO.getPassword());

        User one;
        try {
            one = getOne(queryWrapper);

        }catch (Exception e){
            logger.error(String.valueOf(e));
            throw new ServiceException(Constants.SYSTEM_CUSTOM_ERROR,"系统错误！");

        }
        return one;

    }
}
